import 'package:love_app/common/su.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';


class MySqfite {
  static const _NAME = "love.db"; // 数据库名称
  static final _version = _getVers(); // 版本号
  static Database _database; // 数据库对象

  // 设置创建数据库的路径
  static Future dataBasePath() async {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, _NAME);
    return path;
  }

  // 获取版本号
  static int _getVers() {
    List<int> versList = [
      1,
    ];
    return versList.last;
  }

  // 初始化
  static init() async {
    String path = await dataBasePath();
    _database = await openDatabase(
      path,
      version: _version,
      onUpgrade: (Database db, int oldVersion, int newVersion){
        print("数据库需要升级！旧版：$oldVersion,新版：$newVersion");
      },
      onCreate: (Database db,int version) async{},
    );
  }

  //判断表是否存在
  static Future<bool> isTableExits(String tableName) async {
    await getCurrentDatabase();
    var res=await _database.rawQuery("select * from Sqlite_master where type = 'table' and name = '$tableName'");
    return res!=null && res.length >0;
  }

  //获取当前数据库对象
  static Future<Database> getCurrentDatabase() async {
    if(_database == null){
      await init();
    }
    return _database;
  }

    ///关闭
  static close() {
    _database?.close();
    _database = null;
  }
}
